<?
require_once("ericdingle/model/BaseProvider.php");
require_once("ericdingle/model/label/LabelEntity.php");

class LabelProvider extends BaseProvider {
	public static function getInstance() {
		return parent::getInstance(__CLASS__);
	}
	
	// CRUD
	
	public function create($label) {
		$labelID = $this->dataInterface_->executeNonQuery(sprintf(
			"INSERT INTO Label (LabelID, Label) " .
			"VALUES (NULL, '%s')",
			$this->dataInterface_->sanitize($label->getLabel())
		));
		
		$label->setLabelID($labelID);
	}
	
	public function read($label = null, $orderBy = null, $limit = null) {
		if (!$orderBy) $orderBy = "L.Label ASC";
		
		$result = $this->dataInterface_->executeQuery(
			"SELECT L.LabelID, L.Label " .
			"FROM Label L " .
			($label ? "WHERE " . $this->getContraints($label) . " " : "") .
			"ORDER BY $orderBy"
		);
		
		if (!$result) {
			die($this->dataInterface_->getError());
		}
		
		$labels = array();
		while ($row = $this->dataInterface_->getNextRow($result)) {
			array_push($labels, $this->loadEntity($row));
		}
		
		return $labels;
	}
	
	public function update($label) {
		$this->dataInterface_->executeNonQuery(sprintf(
			"UPDATE Label " .
			"SET Label = '%s'" .
			"WHERE LabelID = %d",
			$this->dataInterface_->sanitize($label->getLabel()),
			$label->getLabelID()
		));	
	}
	
	public function delete($label) {
		$this->dataInterface_->executeNonQuery(sprintf(
			"DELETE FROM Label " .
			"WHERE LabelID = %d",
			$label->getLabelID()
		));
	}
	
	// Helpers
	
	private function getConstraints($label) {
		$constraints = array();
		if ($labelID = $label->getLabelID()) {
			array_push($constraints, sprintf("L.LabelID = %d", $labelID));
		}
		return implode(" AND ", $constraints);
	}
	
	private function loadEntity($row) {
		return new LabelEntity(
			$row["LabelID"],
			$row["Label"]
		);
	}
}
?>
